var express = require('express');
var router = express.Router();
let db = require('../tools/Db');
let to = require('../tools/to');

router.get('/',function(req,res,next){
    res.json({code:200,data:null,msg:'欢迎小U课堂项目'});
})


//首页课程信息
router.get('/courseinfo/:type',async(req,res,next)=>{
    let type = req.params.type;
    let sql = "SELECT id,cid,title,price,CONCAT('uploads/course/',image_src) AS image_src,type_name,area_name,subject_name FROM e_course WHERE type=? limit 0,8"
    let [err,result] = await to(db.query(sql,[type]));
    if(!err){
        res.json({code:200,data:result,msg:'数据获取成功'});
    }else{
        next(err);
    }
})

//搜索
//keyword 搜索的关键词
//page 当前页码
//pagesize 页面上显示条数
//totalNum 总记录数
router.get('/searchlist',async(req,res,next)=>{
    //获取参数
    //数据库查询
    //获取总记录数
    let keyword = req.query.keyword;
    // console.log(keyword);
    let sql = `select * from e_course where title like '%${keyword}%' limit ?,?`;
    let {page=1,pagesize=10,type=1} = req.query;
    let start = (page - 1) * pagesize;
    let[{totalNum}] = await db.query(`select count(id) as totalNum from e_course where title like '%${keyword}%'`,[type]);
    let [err,result] = await to(db.query(sql,[start,parseInt(pagesize)]));

    
    let data = {
        page:parseInt(page),
        pagesize:parseInt(pagesize),
        totalNum,
        keyword,
        result
    }
    // console.log(data);
    if(!err){
        res.json({code:200,data,msg:'搜索数据获取成功'});
    }else{
        next(err);
    }
})

router.get('/banner',async(req,res)=>{
    let {id,image_src,title,isshow} = req.query;
    let sql = "select * from e_banners where isshow=1";
    let result = await db.query(sql,[id,image_src,title,isshow]);
    if(result.length){
        res.json({code:200,data:result,msg:'数据获取成功'});
    }else{
        res.json({code:202,data:result,msg:''});
    }
})
module.exports = router;